package com.platform.module.admin.aspect;

import com.platform.module.dao.config.db.DS;
import com.platform.module.dao.config.db.DynamicDataSourceHolder;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
@Order(1)
public class DynamicDataSourceAspect {
    private static final Logger log = LoggerFactory.getLogger(DynamicDataSourceAspect.class);
    private final String DEFAULT_DATA_SOURCE = "db1";

    @Pointcut("execution(public * com.platform.module.dao.service.*.*(..))")
    public void dataSourcePoint() {
    }

    @Before("dataSourcePoint()")
    public void before(JoinPoint joinPoint) {
        Object target = joinPoint.getTarget();
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        String methodName = methodSignature.getName();
        Class<?>[] parameterTypes = methodSignature.getParameterTypes();

        try {
            Method method = target.getClass().getInterfaces()[0].getMethod(methodName, parameterTypes);
            String dataSource = DEFAULT_DATA_SOURCE;
            if (method.isAnnotationPresent(DS.class)) {
                DS DS = method.getAnnotation(DS.class);
                dataSource = DS.value();
            }

            DynamicDataSourceHolder.setDataSource(dataSource);
        } catch (Exception var9) {
            log.info("error", var9);
        }

    }

    @After("dataSourcePoint()")
    public void after(JoinPoint joinPoint) {
        DynamicDataSourceHolder.clear();
    }
}
